import React, {useEffect, useState, forwardRef, useImperativeHandle, useRef} from 'react';
import PageModule from "@/components/PageModule.tsx";
import {Form, Row, Table, Button, message} from "antd";
import CycleForm from "@/components/DynamicSearchForm/CycleForm.tsx";
import PageActionBar from "@/components/PageActionBar.tsx";
import {findDicNameForDicCode, getDicOnCode} from "@/utils/dicAll.ts";
import {nameOfPeople, nameOfPeople2, validateIdCard, verificationOfFixedPhoneNumber} from "@/utils/regular.ts";
import SelectCustomer from "@/views/policyManagement/car/SelectCustomer.tsx";

const InsuredInfo = forwardRef(({carInsuredInfo, insure, policyDisabled}, ref) => {
    useImperativeHandle(ref, () => ({
        verifyTheForm: () => {
            setShow(false)
            if (!dataSource.length) {
                message.error('被保人信息最少一条')
                return false
            }
            return dataSource.reduce((res, item) => {
                const obj = {
                    ...item,
                    ...item.addressPart
                }
                delete obj.addressPart
                res.push(obj)
                return res
            }, [])
        }
    }))
    const [InsuredForm] = Form.useForm()
    const [rowIndex, setRowIndex] = useState(undefined)
    const [dataSource, setDataSource] = useState([])
    const [formDisabled, setFormDisablede] = useState(false)
    useEffect(() => {
        countRef.current = insure
    }, [insure]);
    // 解决必投保人信息旧值问题
    const countRef = useRef(insure);
    const btnList = [
        {
            name: '新增',
            type: 'primary',
            onClick: () => {
                setShow(true)
            }
        }
    ]
    const columns = [
        {
            title: '操作',
            key: 'action',
            render: (_, record, index) => (
                <div className="table-options">
                    <span className="operation_style"
                          onClick={() => lookOrEdit('details', record, undefined)}>查看</span>
                    {!policyDisabled&&<span className="operation_style"
                          onClick={() => lookOrEdit('edit', record, index)}>修改</span>}
                    {!policyDisabled &&<span className="operation_style danger" onClick={() => deleteRow(index)}>删除</span>}
                </div>
            ),
            align: 'center',
            width: 140
        },
        {title: '被保人名称', dataIndex: 'custName', key: 'custName'},
        {
            title: '证件类型', dataIndex: 'certiType', key: 'certiType',
            render: (value) => <>{findDicNameForDicCode('PRODUCT.IDCARDTYPE', value)}</>,
        },
        {title: '证件号码', dataIndex: 'certiNo', key: 'certiNo'}
    ]
    const relationChange = (value: string) => {
        if (value === '001') {
            InsuredForm.setFieldsValue({
                custName: countRef.current.insurerName,
                certiType: countRef.current.certiType,
                contactName: countRef.current.contactName,
                countryCode: countRef.current.countryCode,
                certiNo: countRef.current.certiNo,
                phone: countRef.current.phone,
                address: countRef.current.address,
                addressPart: countRef.current.addressPart
            })
        }
    }

    const [formFields, setFormFields] = useState([
        {
            type: 'select',
            name: 'relation',
            label: '与投保人关系',
            placeholder: '请选择',
            options: getDicOnCode("POLICY.INSURED.RELATION"),
            rules: [{required: true, message: '请选择与投保人关系'}],
            onChange: relationChange
        },
        {
            type: 'select',
            name: 'certiType',
            label: '证件类型',
            placeholder: '请选择',
            options: getDicOnCode("PRODUCT.IDCARDTYPE"),
            rules: [{required: true, message: '请选择证件类型'}],
        },
        {
            type: 'input',
            name: 'contactName',
            label: '联系人姓名',
            rules: [{required: true, message: '请输入联系人姓名'}, {validator: nameOfPeople2}]
        },
        {
            type: 'input',
            name: 'custName',
            label: '被保人名称',
            rules: [{required: true, message: '请输入被保人名称'}, {validator: nameOfPeople}]
        },
        {
            type: 'input',
            name: 'certiNo',
            label: '证件号码',
            dependencies: ['certiType'],
            rules: [{required: true, message: '请输入证件号码'},
                {min: 7, message: '请输入证件号码至少7个字符'},
                ({getFieldValue}) => ({
                    validator(_, value) {
                        const Type = getFieldValue('certiType')
                        if (!Type) {
                            return Promise.resolve()
                        }
                        if (Type === '1') {
                            return validateIdCard(value)
                        }
                    },
                })]
        },
        {
            type: 'input',
            name: 'phone',
            label: '联系人电话',
            rules: [{required: true, message: '请输入联系人电话'}, {validator: verificationOfFixedPhoneNumber}]
        },
        {
            type: 'select',
            name: 'countryCode',
            label: '国别',
            options: getDicOnCode("PRODUCT.ALLTRUST_COUNTRY"),
            disabled: true,
        },
        {
            type: 'AddressPart',
            name: 'addressPart',
            label: '所在省市区/县',
            span: 16,
            labelCol: {span: 3},
            rules: [{required: true, message: '所在省市区/县'}],
        },
        {
            type: 'TextArea',
            name: 'address',
            label: '通讯地址',
            rules: [{required: true, message: '请输入通讯地址'}],
            pull: 6,
            span: 24,
        },
    ])
    const [show, setShow] = useState(false)
    const lookOrEdit = (type, record, index): void => {
        setRowIndex(index)
        record.countryCode = record.countryCode || '008zg'
        if (record.provinceCode || record.cityCode || record.regionCode) {
            record.addressPart = {
                provinceCode: record.provinceCode,
                provinceName: record.provinceName,
                cityCode: record.cityCode,
                cityName: record.cityName,
                regionCode: record.regionCode,
                regionName: record.regionName
            }
        }
        InsuredForm.setFieldsValue(record)
        setShow(true)
        setFormDisablede(type === 'details')
    }
    // 删除
    const deleteRow = (index: number) => {
        setDataSource(dataSource.filter((_, i) => i !== index))
    }
    const cancel = () => {
        setShow(false)
        InsuredForm.resetFields()
        setFormDisablede(false)
    }
    const onFinish = (values: any) => {
        console.log('Success:', values);
        if (rowIndex !== undefined) {
            const list = [...dataSource]
            list[rowIndex] = values
            setDataSource(list)
        } else {
            setDataSource([...dataSource, values]);
        }
        setShow(false)
        InsuredForm.resetFields()
    }
    useEffect(() => {
        if (!carInsuredInfo || !carInsuredInfo.length) return
        setDataSource(carInsuredInfo)
    }, [carInsuredInfo])
    const buttons = () => {
        return (
            <>
                <PageActionBar btnList={btnList} inline />
                {show ? <SelectCustomer onSure={(item) => {
                    InsuredForm.setFieldsValue({
                        custName: item.custName || undefined,
                        certiType: item.certiType || undefined,
                        contactName: item.contactName || undefined,
                        countryCode: item.countryCode || '008zg',
                        certiNo: item.certiNo || undefined,
                        phone: item.phone || undefined,
                        address: item.address || undefined,
                        addressPart: {
                            provinceCode: item.provinceCode || undefined,
                            provinceName: item.provinceName || undefined,
                            cityCode: item.cityCode || undefined,
                            cityName: item.cityName || undefined,
                            regionCode: item.regionCode || undefined,
                            regionName: item.regionName || undefined,
                        }
                    })
                }} /> : null}
            </>
        )
    }


    return (
        <PageModule title="被保人信息" btns={!policyDisabled ? buttons() : null}>
            <Table dataSource={dataSource} columns={columns} bordered={true} size="middle" pagination={false} />
            <Form
                layout="horizontal"
                autoComplete="off"
                labelCol={{span: 8}}
                wrapperCol={{span: 16}}
                form={InsuredForm}
                style={{marginTop: 20, display: show ? 'block' : 'none'}}
                onFinish={onFinish}
                initialValues={
                    {countryCode: '008zg'}
                }
                disabled={formDisabled}
            >
                <Row>
                    <CycleForm fields={formFields} />
                </Row>
                <Form.Item wrapperCol={{offset: 2}}>
                    <Button className="mr15" type="primary" htmlType="submit">保存</Button>
                    <Button onClick={cancel} disabled={false}>取消</Button>
                </Form.Item>
            </Form>
        </PageModule>
    );
})
export default InsuredInfo;